package com.lagou.loadbalance;

import com.lagou.register.ZkUtil;
import org.apache.curator.framework.CuratorFramework;

import java.util.List;

public class AvailabilityFilteringRule implements IRule{


    /**
     * 根据描述, 应该是选取最近有接收过请求的server, 表明此服务最大可能性还存活
     * @param zkClient
     * @return
     */
    @Override
    public String choose(CuratorFramework zkClient) {

        List<String> serviceList = ZkUtil.getServiceList(zkClient);

        String chooseServer = null;

        try {
            if (null != serviceList && !serviceList.isEmpty()) {

                long now = System.currentTimeMillis();

                long shortest = 0;
                for (String service : serviceList) {
                    byte[] bytes = zkClient.getData().forPath("/" + service);
                    String s = new String(bytes);
                    System.out.println(s);
                    if (null != s){
                        long timestamp = Long.parseLong(s);
                        long diff = (now - timestamp)/1000;
                        /**
                         * 最后请求超过5秒, 我们认为实例节点可用性低
                         * 小于5秒则对比谁最近被调用过
                         */
                        if (diff < 5000){
                            if (shortest == 0 || diff < shortest){
                                shortest = diff;
                                chooseServer = service;
                            }
                        }
                    }
                }

                if (null == chooseServer){
                    /**
                     * 随机选一个
                     */
                    int index = (int)(Math.random() * serviceList.size());
                    chooseServer = serviceList.get(index);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return chooseServer;
    }
}
